<?php

/**
 * Created by PhpStorm.
 * User: thorjiang
 * Date: 2018/5/9
 * Time: 15:19
 */

namespace App\Http\Controllers;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Symfony\Component\HttpFoundation\File\File;

/**
 *
 * Class AppBaseController
 * @package App\Http\Controllers
 */
class AppBaseController extends Controller
{
    public $userId;
    public $userInfo;

    /**
     * 成功响应
     * @param $data
     * @param string $msg
     */
    protected function sendResponse($data, $msg = 'ok')
    {
        return getSuccessResponse($data, $msg);
    }

    /**
     * 失败响应
     * @param $msg
     * @param $code
     */
    protected function sendError($msg, $code = 1, $data = null)
    {
        return getErrorResponse($code, $msg, $data);
    }

    /**
     * @param $token
     */
    protected function checkAuth($token = null)
    {
        if (empty($token)) {
            $token = $this->request->header('token');
        }
        $userId = Cache::getUserToken($token);

        if ($userId === false) {
            die('{"code":2,"msg":"unauthorized"}');
        }

        $user = User::getInfo($userId);
        if ($user['status'] != 0) {
            $ret = ['code' => 2, 'msg' => "您已被封号（ID：{$userId}），请联系客服"];
            throwResponseException(2, "您已被封号（ID：{$userId}），请联系客服");
        }

        $this->userId = $userId;
        $this->userInfo = $user;
    }

    /**
     * @param $image
     * @param string $prefix
     */
    protected function uploadQiniu($image, $key)
    {
        $accessKey = config('customer.qiniu_ak');
        $secretKey = config('customer.qiniu_sk');
        $bucket = config('customer.qiniu_bucket');

        $auth = new Auth($accessKey, $secretKey);
        $token =  $auth->uploadToken($bucket);
        // 要上传文件的本地路径
        $filePath = $image->getRealPath();
        // 上传到七牛后保存的文件名

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        return [$ret, $err];
    }
}
